/**判断输入字符和已有数组里的字符相似度是否达到80% */
export const similarity = (s1: any, s2: any, p: number) => {
  // 计算两个字符串之间的 Levenshtein 距离
  const distance = levenshteinDistance(s1, s2)
  // 计算相似度得分
  const score = 1 - distance / Math.max(s1.length, s2.length)
  // 判断相似度是否达到 90%
  return score >= p
}

// 计算两个字符串之间的 Levenshtein 距离
const levenshteinDistance = (s1: any, s2: any) => {
  const n = s1.length
  const m = s2.length
  if (n === 0 || m === 0) {
    return n + m
  }

  const matrix = []
  for (let i = 0; i <= n; i++) {
    matrix[i] = [i]
  }

  for (let j = 0; j <= m; j++) {
    matrix[0][j] = j
  }

  for (let i = 1; i <= n; i++) {
    for (let j = 1; j <= m; j++) {
      if (s1.charAt(i - 1) === s2.charAt(j - 1)) {
        matrix[i][j] = matrix[i - 1][j - 1]
      } else {
        matrix[i][j] = Math.min(matrix[i - 1][j], matrix[i][j - 1], matrix[i - 1][j - 1]) + 1
      }
    }
  }

  return matrix[n][m]
}

// 测试代码
// const array = ["apple", "banana", "orange"]
// const input = "appel"
// for (let i = 0; i < array.length; i++) {
//   if (similarity(input, array[i])) {
//     console.log(`${input} 和 ${array[i]} 相似度达到了 80%`)
//   }
// }
